package com.zhai.domain.strategy.service.rule.chain.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.zhai.domain.activity.repository.IActivityRepository;
import com.zhai.domain.strategy.repository.IStrategyRepository;
import com.zhai.domain.strategy.service.armory.IStrategyDispatch;
import com.zhai.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.zhai.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import com.zhai.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: 权重责任链节点
 * @ClassName: RuleWeightLogicChain
 * @Author: zhaiyongxin
 * @Date: 2025/1/9 14:35
 * @Version: 1.0
 */
@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    protected IStrategyRepository strategyRepository;
    @Resource
    protected IStrategyDispatch strategyDispatch;
    @Resource
    protected IActivityRepository activityRepository;


    /**
     * 权重责任链过滤；
     * 1. 权重规则格式；4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
     * 2. 解析数据格式；判断哪个范围符合用户的特定抽奖范围
     */
    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        String ruleValue = strategyRepository.queryStrategyRuleValue(strategyId, ruleModel());
        // 3.如果存在权重规则，找到符合条件的规则范围奖品列表
        Map<Long, String> analyticalValueGroup = getAnalyticalValue(ruleValue);
        if (CollectionUtil.isEmpty(analyticalValueGroup)) {
            return next().logic(userId, strategyId);
        }
        //4.获取积分列表，找到用户积分符合权重的最大范围值是多少
        List<Long> analyticalSortedKeys = new ArrayList<>(analyticalValueGroup.keySet());
        //倒序排列
        Collections.sort(analyticalSortedKeys,Comparator.reverseOrder());

        // 查询用户抽奖总次数
        Integer userScore = activityRepository.queryRaffleActivityAccountTotalPartakeCount(strategyId, userId);
        Long nextValue = analyticalSortedKeys.stream()
                .filter(key -> userScore >= key)
                .findFirst()
                .orElse(null);
        if (null != nextValue) {
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValueGroup.get(nextValue));
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }
        // 5. 过滤其他责任链
        log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        return next().logic(userId, strategyId);

    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }
    /**
     * 根据权重值进行分组 key-积分 value-redis键值
     * @param ruleValue
     * @return
     */
    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleValueMap = new HashMap<>();
        for (String ruleValueKey : ruleValueGroups) {
            // 检查输入是否为空
            if (ruleValueKey == null || ruleValueKey.isEmpty()) {
                return ruleValueMap;
            }
            // 分割字符串以获取键和值
            String[] parts = ruleValueKey.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            ruleValueMap.put(Long.parseLong(parts[0]), ruleValueKey);
        }
        return ruleValueMap;
    }
}
